<?php

namespace Home\Controller;

use Common\Model\ErrorLogModel;
use Common\Model\GoodsModel;
use Common\Model\OrderModel;
use Common\Model\OrderPiaofutongModel;
use Common\Model\OrderSubModel;
use Think\Controller;
use Vendor\Zhiyoubao\Zhiyoubao\Zhiyoubao;

class PaymentController extends Controller
{
    private $pay_type;

    function index()
    {
        $data = I('get.');
        $order_id = $data['order_id'];
        $model_order = new OrderModel();
        $info_order = $model_order->find($order_id);
        $this->pay_type = $info_order['pay_type'];
        if (!$info_order or !$order_id)
            $this->error('找不到订单' . $order_id);
        if (!$info_order or !$order_id)
            $this->error('找不到统一订单号' . $order_id);
        $model_goods = new GoodsModel();
        $info_goods = $model_goods->where(array('id' => $info_order['goods_id']))->find();
        if ($info_order['num'] > $info_goods['stock']) {
            echo "<script>alert('您购买的数量超过了商品库存！请调整购买数量！');</script>";
            exit();
        }
        $this->assign('info_order', $info_order);
        $this->assign('info_goods', $info_goods);

        $this->display();
    }


    // 智游宝 支付成功 回调函数
    function zhiyoubao_unionOrderNumCallback()
    {
        $data = I('get.');
        $get_order_code = $data['order_code'];

        $model_order = new OrderModel();
        $where_order = array('order_code' => $get_order_code);
        $info_order = $model_order->where($where_order)->find();

        if (!$info_order)
            $this->error('找不到订单！' . $get_order_code, true);

        $order_id = $info_order['id'];

        // 给 用户 的 订单 改变状态 -> 支付成功
        $save_is_pay = array('is_pay' => 1, 'paytime' => time());
        if (!$model_order->where(array('id' => $order_id))->save($save_is_pay))
            $this->error('订单：' . $order_id . '的 is_pay 修改失败！', true);

        // 提交 智游宝 下单
        $this->zhiyoubao_api_request($info_order);

        // 修改商品的 库存 信息
        $model_goods = new GoodsModel();
        $num = $info_order['num'];
        $where_goods = array('id' => $info_order['goods_id']);
        $stock = $model_goods->where($where_goods)->getField('stock');
        if (intval($stock) - intval($num) < 0) {
            $this->error('订单：' . $info_order['id'] . '缺货！' . ' 购买人ID：' . $info_order['user_id'] . ' 昵称：' . $info_order['nick_name'] . ' 电话：' . $info_order['phone'], true);
        } else {
            $is_dec = $model_goods->where($where_goods)->setDec('stock', $num);
            if (!$is_dec)
                $this->error('订单：' . $info_order['id'] . '减仓失败！' . ' 购买人ID：' . $info_order['user_id'] . ' 昵称：' . $info_order['nick_name'] . ' 电话：' . $info_order['phone'], true);
        }
    }

    // 票付通 支付成功 回调
    function piaofutong_unionOrderNumCallback()
    {
        $data = I('get.');
        $order_code = $data['order_code'];
        $req_sign = $data['sign'];

//        $this->errFile('pay_callback'.$order_code);

        $model_order = new OrderModel();
        $where_order = array('order_code' => $order_code);
        $info_order = $model_order->where($where_order)->find();
        $sign = $data['sign'];
        if ($sign !== $req_sign)
            $this->error('签名不正确', true);

        if (!$info_order)
            $this->error('找不到订单！' . $order_code, true);

        $order_id = $info_order['id'];

        // 给 用户 的 订单 改变状态 -> 支付成功
        $save_is_pay = array('is_pay' => 1, 'paytime' => time());
        if (!$model_order->where(array('id' => $order_id))->save($save_is_pay))
            $this->error('订单：' . $order_id . '的 is_pay 修改失败！', true);

        // 提交 票付通 下单
        vendor('Piaofutong.Piaofutong');
        $piaofutong = new \Piaofutong();
        $model_order_sub = new OrderSubModel();
        $model_order_piaofutong = new OrderPiaofutongModel();
        $list_order_sub = $model_order_sub->where(array('order_code' => $order_code))->select();

        foreach ($list_order_sub as $order_sub) {
            $lid = $order_sub['seller_id']; // 景区ID
            $tid = $order_sub['ticket_id']; // 门票id
            $m = $order_sub['a_id']; // 供应商id

//            $lid = 2633;
//            $tid = 5715;
//            $m = 113;

            $tprice = floatval($order_sub['price']) * 100;
            $num = $order_sub['num'];
            $personId = $order_sub['certificate_no'];
            $ordername = $order_sub['real_name'];
            $ordertel = $order_sub['mobile'];
            $play_time = $order_sub['playtime'];
            $order_sub_id = $order_sub['id'];
            $sub_order_code = $order_sub['sub_order_code'];
            $paymode = 0;

            $req_order_submit = $piaofutong->order_submit(
                $lid, $tid, $m, $sub_order_code, $tprice, $num, $personId, $play_time, $ordername, $ordertel, $ordertel, $paymode
            );

            if (!$req_order_submit['success'])
                $this->error('订单' . $order_id . '子订单' . $order_sub_id . '提交远端订单 失败！' . ' 错误：' . $req_order_submit['info'], true);

            // 将订单信息 添加到 票付通专有订单
            $info_submit_piaofutong = $req_order_submit['info'];
            $data_order_piaofutong = array(
                'order_id' => $order_sub_id,
                'ordernum' => $info_submit_piaofutong['ordernum'],
                'remotenum' => $info_submit_piaofutong['remotenum'],
                'code' => $info_submit_piaofutong['code'],
                'qrcodeURL' => $info_submit_piaofutong['qrcodeURL'],
                'UUqrcodeIMG' => $info_submit_piaofutong['UUqrcodeIMG']
            );
            if (!$model_order_piaofutong->create($data_order_piaofutong))
                $this->error($model_order_piaofutong->getError());
            if (!$model_order_piaofutong->add($data_order_piaofutong))
                $this->error('子订单:' . $order_sub_id . '票付通订单 添加失败！', true);

            // 更改订单 api 状态
            $save_is_api = array('is_api' => 1);
            $req_save_is_api = $model_order_sub->where(array('id' => $order_sub_id))->save($save_is_api);
            if (!$req_save_is_api)
                $this->error('订单：' . $order_id . '子订单' . $order_sub_id . '的 is_api 修改失败！', true);

            $save_is_pay = array('is_pay' => 1, 'paytime' => time());
            if (!$model_order_sub->where(array('id' => $order_sub_id))->save($save_is_pay))
                $this->error('订单：' . $order_id . '子订单' . $order_sub_id . '的 is_pay 修改失败！', true);
        }

        $save_is_api = array('is_api' => 1);
        $req_save_is_api = $model_order->where(array('id' => $order_id))->save($save_is_api);
        if (!$req_save_is_api)
            $this->error('订单：' . $order_id . '的 is_api 修改失败！', true);
    }


    private function zhiyoubao_api_request($info_order)
    {
        // 添加订单接口
        $addticket = $this->addTicket($info_order);

        if (!$addticket['status'])
            $this->error('订单：' . $info_order['id'] . ' | 错误信息： ' . $addticket['info'], true);

        // 更改订单 api 状态
        $model_order = new OrderModel();
        $save_is_api = array('is_api' => 1);
        $req_save_is_api = $model_order->where(array('id' => $info_order['id']))->save($save_is_api);
        if (!$req_save_is_api)
            $this->error('订单：' . $info_order['id'] . '的 is_api 修改失败！', true);
    }


    private function addTicket($order)
    {
        $certificateNo = $order['certificate_no'];
        $linkName = $order['nick_name'];
        $linkMobile = $order['phone'];
        $main_orderCode = $order['order_code'];
        $num = $order['num'];
        $orderPrice = $order['price'];
        $sub_orderCode = $order['sub_order_code'];
        $price = $order['price'];
        $totalPrice = $order['total_price'];
        $playDate = date('Y-m-d', $order['playtime']);
        $goodsName = getFieldByModel('name', 'Goods', $order['goods_id'], '找不到商品');
        $payMethod = $order['pay_type'];
        vendor("Zhiyoubao.Zhiyoubao");
        $zhiyoubao = new Zhiyoubao(C('MAG_APP_URL'));
        $req = $zhiyoubao->addOrder($certificateNo, $linkName, $linkMobile, $main_orderCode, $orderPrice, $sub_orderCode, $price, $num, $totalPrice, $playDate, $goodsName, $payMethod);
        return $req;
    }

    function changeNum()
    {
        $data = I('get.');
        $order_id = $data['order_id'];
        $num = $data['num'];
        $model_order = new OrderModel();
        $model_goods = new GoodsModel();

        $info_order = $model_order->find($order_id);
        $info_goods = $model_goods->find($info_order['goods_id']);
        if (!$info_order)
            $this->error('找不到订单！');
        if (intval($info_goods['stock']) < intval($num))
            $this->error('没有那么多库存！');
        $total_price = floatval($info_goods['price']) * intval($num);
        $save = array('num' => $num, 'total_price' => $total_price);
        if (!$model_order->where(array('id' => $order_id))->save($save)) {
            $this->addErrorLog('订单：' . $info_order['id'] . '修改订单数量失败！');
            $this->error('修改订单数量失败！');
        } else {
            $req_arr = array(
                'num' => $num,
                'total_price' => $total_price
            );
            $this->success($req_arr);
        }
    }

    function remove_tocket()
    {
        $order_id = I('get.id');
        $mode_order = new OrderModel();
        if ($mode_order->where(array('id' => $order_id))->delete())
            $this->success('订单删除成功', '/index.php/Home');
        else
            $this->error('订单删除失败', '/index.php');
    }

//    复写 error
    protected function error($message = '', $is_log = false, $jumpUrl = '', $ajax = false)
    {
        if ($is_log) {
            $this->addErrorLog($message);
        }
        parent::error($message, $jumpUrl, $ajax);
    }

    protected function addErrorLog($message)
    {
        $model_error_log = new ErrorLogModel();
        $data = array(
            'addtime' => time(),
            'controller' => CONTROLLER_NAME,
            'action' => ACTION_NAME,
            'msg' => $message
        );
        if (!$model_error_log->add($data))
            $this->errFile($message);
    }

    private function errFile($msg)
    {
        $myfile = fopen("errFile.txt", "w");
        fwrite($myfile, $msg);
        fclose($myfile);
    }
}